(function () {
    Ext.define("JncjMenu", {
        extend: 'Ext.menu.Menu',
        fieldName: '',
        filedType: '',
        constructor: function () {
            this.callParent(arguments);
        }
    });
    Ext.override(Ext.Ajax, {
        request: function (options) {
            options = options || {};
            if (options.url && options.url.indexOf('Emp/HrEpmMain/GetEmptipResult') > -1) {
                return;
            }
            var me = this,
                scope = options.scope || window,
                username = options.username || me.username,
                password = options.password || me.password || '',
                async,
                requestOptions,
                request,
                headers,
                xhr;
            if (me.fireEvent('beforerequest', me, options) !== false) {

                requestOptions = me.setOptions(options, scope);

                if (me.isFormUpload(options)) {
                    me.upload(options.form, requestOptions.url, requestOptions.data, options);
                    return null;
                }


                if (options.autoAbort || me.autoAbort) {
                    me.abort();
                }


                async = options.async !== false ? (options.async || me.async) : false;
                xhr = me.openRequest(options, requestOptions, async, username, password);


                if (!me.isXdr) {
                    headers = me.setupHeaders(xhr, options, requestOptions.data, requestOptions.params);
                }


                request = {
                    id: ++Ext.data.Connection.requestId,
                    xhr: xhr,
                    headers: headers,
                    options: options,
                    async: async,
                    binary: options.binary || me.binary,
                    timeout: setTimeout(function () {
                        request.timedout = true;
                        me.abort(request);
                    }, options.timeout || me.timeout)
                };

                me.requests[request.id] = request;
                me.latestId = request.id;

                if (async) {
                    if (!me.isXdr) {
                        xhr.onreadystatechange = Ext.Function.bind(me.onStateChange, me, [request]);
                    }
                }

                if (me.isXdr) {
                    me.processXdrRequest(request, xhr);
                }


                xhr.send(requestOptions.data);
                if (!async) {
                    return me.onComplete(request);
                }
                return request;
            } else {
                Ext.callback(options.callback, options.scope, [options, undefined, undefined]);
                return null;
            }
        }
    });
    var NG = {
        version: '20210928',//版本
        isDetail: true,//是否明细页面
        _contextMenu: null,//右键菜单项
        _ucode: null,
        _helpFieldType: ['ngRichHelp', 'ngComboBox', 'ngOrgHelp', 'ngDeptHelp', 'ngEmpHelp', 'gcWorkCycleRichHelp', 'ngProjectHelp', 'ngEnterpriseHelp', 'ngCustomFileHelp'],//通用帮助类型，lqg20210309添加gcWorkCycleRichHelp/ngProjectHelp，20210329添加ngEnterpriseHelp，20210513添加ngCustomFileHelp
        _batchFieldType: ['ngRichHelp', 'ngComboBox', 'ngOrgHelp', 'ngDeptHelp', 'ngEmpHelp', 'gcWorkCycleRichHelp', 'ngProjectHelp', 'ngEnterpriseHelp', 'ngCustomFileHelp'],//需要执行代码转名称的类型
        _copy: function (v) {
            //将数据复制到剪切板
            var input = document.createElement('input');
            document.body.appendChild(input);
            input.setAttribute('value', v);
            input.select();
            if (document.execCommand('copy')) {
                document.execCommand('copy');
            }
            document.body.removeChild(input);
        },
        _needBatch: function (filedName) {
            //判断字段是否需要执行代码转名称
            var xtp = curForm.getItem(filedName).xtype;
            return this._helpFieldType.includes(xtp) ? true : false;
        },
        _sysLog: function (message) {
            console.log(message);
        },
        _init: function () {
            //初始化NG
            this.isDetail = typeof (otype) == "string" ? true : false;
        },
        _getGrid: function (gridid) {
            if (gridid && gridid != 'undefined') {  //lqg20210217添加 gridid != 'undefined' 条件，以便缺省d表时不报错。
                return Ext.getCmp(gridid + 'grid')
            } else {
                return curGrid;
            }
        },
        _getForm: function () {
            return curForm;
        },
        _getGridColumns: function (gridid) {
            var gridColumns = [];
            if (this.isDetail) {
                if (gridColumns.length == 0) {
                    var cgrid = gridid ? Ext.getCmp(gridid + 'grid') : curGrid;
                    Ext.each(cgrid.columns, function (it, index) {
                        if (it.width) {
                            gridColumns.push({
                                dataIndex: it.dataIndex,
                                hidden: it.hidden,
                                header: it.text,
                                width: it.width,
                                align: it.align,
                                renderer: it.renderer
                            });
                        } else {
                            gridColumns.push({
                                dataIndex: it.dataIndex,
                                hidden: it.hidden,
                                header: it.text,
                                align: it.align,
                                renderer: it.renderer
                            });
                        }
                    });
                }
            }
            return gridColumns;
        },
        _isArray: function (o) {
            //对象是否数组
            return Object.prototype.toString.call(o) == '[object Array]';
        },
        _getExpField: function (exp) {
            //获取表达式中的所有字段名
            var rv = [];
            var offset = 0;
            while (exp.indexOf('{', offset) > -1) {
                var start = exp.indexOf('{', offset);
                var end = exp.indexOf('}', start);
                var newvalue = exp.substring(start + 1, end);
                if (!rv.includes(newvalue)) rv.push(newvalue);
                offset = end + 1;
            }
            return rv;
        },
        _getFirstAttr: function (data) {
            for (var key in data)
                return data[key];
        },
        _getUcode: function () {
            if (!this._ucode) {
                if (window.external) {
                    var vturl = window.external.GetAppInfo('votingurl');
                    var i1 = vturl.indexOf('userCode=');
                    var i2 = vturl.indexOf('&', i1 + 1);
                    this._ucode = vturl.substring(i1 + 9, i2);
                } else {
                    var allscript = document.getElementsByTagName('script');
                    for (var i = 0; i < allscript.length; i++) {
                        if (allscript[i].src.indexOf('NG3Resource/js/eformJs/') > 0) {
                            var src = allscript[i].src;
                            var ii1 = src.indexOf('/eformJs/');
                            var ii2 = src.indexOf('pform', ii1);
                            this._ucode = src.substring(ii1 + 9, ii2).replace('NG', '');
                            break;
                        }
                    }
                }
            }
            return this._ucode;
        },
        _getDetailModel: function (gridid) {
            //获取表体grid的model名
            if (gridid) {
                return gridid + 'model';
            } else {
                return 'p_' + busname.substring(1) + '_dmodel';
            }
        },
        setCombMenu: function () {
            //设置右键菜单
            this._init();
            var needMenuList = [];
            if (curForm.fields) {
                for (var i = 0; i < curForm.fields.length; i++) {
                    if (curForm.fields[i].xtype == "ngRichHelp" || curForm.fields[i].xtype == "ngComboBox") {
                        needMenuList.push(curForm.fields[i]);
                    }
                }
            } else {
                for (var i = 0; i < curForm.fieldRows.length; i++) {
                    for (var j = 0; j < curForm.fieldRows[i].length; j++) {
                        if (curForm.fieldRows[i][j].xtype == "ngRichHelp" || curForm.fieldRows[i][j].xtype == "ngComboBox") {
                            needMenuList.push(curForm.fieldRows[i][j]);
                        }
                    }
                }
            }
            if (!this._contextMenu) {
                this._contextMenu = new JncjMenu();
                var item1 = new Ext.menu.Item();
                item1.setText('复制数据');
                item1.setHandler(function () {
                    var pvalue = curForm.getItem(this.ownerCt.fieldName).getValue();
                    window.NG.copy(pvalue);
                });
                this._contextMenu.add(item1);
                var item2 = new Ext.menu.Item();
                item2.setText('复制显示值');
                item2.setHandler(function () {
                    var pvalue = curForm.getItem(this.ownerCt.fieldName).rawValue;
                    window.NG._copy(pvalue);
                });
                this._contextMenu.add(item2);
            }

            for (var k = 0; k < needMenuList.length; k++) {
                var pi = document.getElementsByName(needMenuList[k].name)[0];
                if (needMenuList[k].xtype == "ngComboBox") {
                    pi.onmouseup = function (ev) {
                        var oEvent = ev || window.event;
                        if (oEvent.ctrlKey && oEvent.button == 2) {
                            NG._contextMenu.fieldName = this.name;
                            NG._contextMenu.filedType = "ngComboBox";
                            NG._contextMenu.showAt(oEvent.clientX, oEvent.clientY);
                        }
                    }
                } else if (needMenuList[k].xtype == "ngRichHelp") {
                    pi.onmouseup = function (ev) {
                        var oEvent = ev || window.event;
                        if (oEvent.ctrlKey && oEvent.button == 2) {//Ctrl+鼠标右键
                            NG._contextMenu.fieldName = this.name;
                            NG._contextMenu.filedType = "ngRichHelp";
                            NG._contextMenu.showAt(oEvent.clientX, oEvent.clientY);
                        }
                    }
                }
            }
        },
        setDetailUnVisible: function (fieldArray, isVisible, gridid) {
            //遍历表体所有列，filedArray中的列名则不显示，否则显示
            this._init();
            if (this._isArray(fieldArray)) {
                Ext.each(fieldArray, function (it, index) {
                    NG._getGrid(gridid).hideColumn(it, isVisible);
                })
            }
        },
        setAllColumnVisible: function (gridid) {
            Ext.each(NG._getGrid(gridid).columns, function (it, index) {
                if (it.hideable) {
                    NG._getGrid(gridid).hideColumn(it.dataIndex, false);
                } else {
                    if (it.getEditor() && NG._helpFieldType.includes(it.getEditor().xtype)) {
                        NG._getGrid(gridid).hideColumn(it.dataIndex, false);
                    }
                }
            })
        },
        setSumToMaster: function (m_field, d_field, gridid) {
            //表体求sum到表头
            var sumtomaster = function () {
                var sumvalue = 0;
                Ext.each(NG._getGrid(gridid).getStore().data.items, function (it, ii) {
                    var eachvalue = it.data[d_field];
                    if (eachvalue) {
                        eachvalue = parseFloat(eachvalue);
                    } else {
                        eachvalue = 0;
                    }
                    sumvalue += eachvalue;
                });
                NG.setValue(m_field, sumvalue);
            }
            NG._getGrid(gridid).getStore().on('add', function () {
                sumtomaster()
            });
            NG._getGrid(gridid).getStore().on('update', function (p1, p2, p3, p4) {
                sumtomaster();
            });
            NG._getGrid(gridid).getStore().on('remove', function (p1, p2, p3, p4) {   //lqg20210222
                sumtomaster();
            });
        },
        bindMasterExp: function (m_field, exp) {
            //为表头字段绑定表达式
            var expFields = this._getExpField(exp);
            var update_m_field = function () {
                var exp2 = exp;
                for (var i = 0; i < expFields.length; i++) {
                    //判断字段类型是下拉或者通用帮助，取rawValue
                    var xtp = curForm.getItem(expFields[i]).xtype;
                    if (NG._helpFieldType.includes(xtp)) {
                        exp2 = exp2.replace(new RegExp('{' + expFields[i] + '}', 'g'), "curForm.getItem('" + expFields[i] + "').getRawValue()");
                    } else if (xtp == 'ngCheckbox') {
                        exp2 = exp2.replace(new RegExp('{' + expFields[i] + '}', 'g'), "(curForm.getItem('" + expFields[i] + "').getValue()==true?curForm.getItem('" + expFields[i] + "').boxLabel:'')");
                    } else {
                        exp2 = exp2.replace(new RegExp('{' + expFields[i] + '}', 'g'), "curForm.getItem('" + expFields[i] + "').getValue()");
                    }
                }
                NG._sysLog(exp2);
                var evvalue = eval(exp2);
                NG.setValue(m_field, evvalue);
            };
            for (var i = 0; i < expFields.length; i++) {
                var xtp = curForm.getItem(expFields[i]).xtype;
                if (NG._helpFieldType.includes(xtp)) {
                    curForm.getItem(expFields[i]).on('helpselected', function (p1, p2) {
                        setTimeout(update_m_field, 1500);//20210623解决代码转名称无法获取名称
                    });
                    curForm.getItem(expFields[i]).on('change', function (p1, p2) {
                        setTimeout(update_m_field, 1500);
                    });
                } else {
                    curForm.getItem(expFields[i]).on('change', function (p1, p2) {
                        update_m_field();
                    });
                }
            }
        },

        updateMasterFieldExp: function (m_field, exp) {  //李庆广：20210507新增
            //根据表达式更新表头字段的值，与上个方法的区别是本方法需要放到监听事件中。
            var expFields = this._getExpField(exp);
            var exp2 = exp;
            for (var i = 0; i < expFields.length; i++) {
                //判断字段类型是下拉或者通用帮助，取rawValue
                var xtp = curForm.getItem(expFields[i]).xtype;
                if (NG._helpFieldType.includes(xtp)) {
                    exp2 = exp2.replace(new RegExp('{' + expFields[i] + '}', 'g'), "curForm.getItem('" + expFields[i] + "').getRawValue()");
                } else {
                    exp2 = exp2.replace(new RegExp('{' + expFields[i] + '}', 'g'), "curForm.getItem('" + expFields[i] + "').getValue()");
                }
            }
            NG._sysLog(exp2);
            var evvalue = eval(exp2);
            NG.setValue(m_field, evvalue);
        },

        bindDetailExp: function (d_field, exp, gridid) {
            //为表体字段绑定表达式
            var expFields = this._getExpField(exp);
            var update_d_field = function () {
                //获取选中行对应的字段值，替换表达式并执行表达式，然后更新到指定字段
                for (var i = 0; i < NG._getGrid(gridid).getStore().data.items.length; i++) {
                    var exp2 = exp;
                    for (var j = 0; j < expFields.length; j++) {
                        exp2 = exp2.replace(new RegExp('{' + expFields[j] + '}', 'g'), "NG._getGrid('" + gridid + "').getStore().data.items[" + i + "].data." + expFields[j]);
                    }
                    var evvalue = eval(exp2);
                    //NG._getGrid(gridid).getStore().data.items[i].data[d_field] = evvalue;
                    NG._getGrid(gridid).getStore().data.items[i].set(d_field, evvalue);//2021-4-19
                }
                NG._getGrid(gridid).getView().refresh();
            };
            NG._getGrid(gridid).getStore().on('add', function (p1, p2, p3, p4) {
                var exp2 = exp;
                for (var j = 0; j < expFields.length; j++) {
                    exp2 = exp2.replace(new RegExp('{' + expFields[j] + '}', 'g'), "NG._getGrid('" + gridid + "').getStore().data.items[" + p3 + "].data." + expFields[j]);
                }
                var evvalue = eval(exp2);
                NG._getGrid(gridid).getStore().data.items[p3].set(d_field, evvalue);
            });
            NG._getGrid(gridid).getStore().on('update', function (p1, p2, p3, p4) {
                if (expFields.includes(p4[0])) {
                    var exp2 = exp;
                    var newindex = NG._getGrid(gridid).getStore().indexOf(p2);
                    for (var j = 0; j < expFields.length; j++) {
                        exp2 = exp2.replace(new RegExp('{' + expFields[j] + '}', 'g'), "NG._getGrid('" + gridid + "').getStore().data.items[" + newindex + "].data." + expFields[j]);
                    }
                    var evvalue = eval(exp2);
                    NG._getGrid(gridid).getStore().data.items[newindex].set(d_field, evvalue);
                }
            });
            update_d_field();
        },
        excuteExp: function (exp) {  //李庆广20210515优化，在不使用pow（）函数时进行千分符替换，使用pow（）时不替换。可进一步优化。
            //计算表达式
            //1.处理中文括号
            //2.将开方、平方替换为js的开方、平方
            exp = exp.toLowerCase(); //转小写，lqg20210515

            exp = exp.replace(/（/g, '(');
            exp = exp.replace(/）/g, ')');
            exp = exp.replace(/，/g, ',');
            exp = exp.replace(/%/g, '/100');
            exp = exp.replace(/sqrt/g, 'Math.sqrt');
            if (exp.indexOf("pow(") == -1) {  //千分符出现在公式中的情景一般是复制某个数值，然后进行其他计算，同时使用pow()的可能性很小。
                exp = exp.replace(/,/g, '');
            } else { //当使用pow()时，一般而言是手工输入公式计算工程量等，不可能出现千分符。
                exp = exp.replace(/pow/g, 'Math.pow');
            }

            try {
                return eval(exp);
            } catch (err) {
                this.alert("公式错误，请检查");
                console.log(err);
                return null;
            }
        },
        bindExcuteExp: function (expField, valueField, gridid) {
            //绑定表体里计算列和值列，计算列中值变化时，自动更新到值列
            NG._getGrid(gridid).getColumn(expField).getEditor().addListener('blur', function (p1) {
                var evvalue = NG.excuteExp(p1.getValue());
                NG._getGrid(gridid).getSelectionModel().getSelection()[0].data[valueField] = evvalue;
                NG._getGrid(gridid).getView().refresh();
            });
        },
        setSpliceToMaster: function (m_field, d_field, separator, gridid) {
            //拼接列表字段字符串到表头
            var update_master_field = function () {
                var splicevalue = '';
                Ext.each(NG._getGrid(gridid).getStore().data.items, function (it, ii) {
                    if (!splicevalue) {
                        splicevalue = it.data[d_field]
                    } else {
                        splicevalue += separator + it.data[d_field];
                    }
                });
                NG.setValue(m_field, splicevalue);
            }
            NG._getGrid(gridid).getStore().on('add', function () {
                update_master_field()
            });
            NG._getGrid(gridid).getStore().on('update', function (p1, p2, p3, p4) {
                if (d_field == p4) {
                    update_master_field();
                }
            });
            NG._getGrid(gridid).getStore().on('remove', function () {  //lqg20210222
                update_master_field();
            });

        },

        //-------------------lqg20210129-----
        setSpliceToMasterNoRep: function (m_field, d_field, separator, gridid) {
            //拼接列表字段字符串到表头(去重)
            var update_master_field = function () {
                var splicevalue = '';
                var arr = [];
                Ext.each(NG._getGrid(gridid).getStore().data.items, function (it, ii) {
                    if (!splicevalue) {
                        splicevalue = it.data[d_field];
                        arr.push(it.data[d_field]);
                    } else if (arr.indexOf(it.data[d_field]) == -1) {  //判断是否在新数组中
                        splicevalue += separator + it.data[d_field];
                        arr.push(it.data[d_field]);
                    }
                });
                NG.setValue(m_field, splicevalue);
            }
            NG._getGrid(gridid).getStore().on('add', function () {
                update_master_field()
            });
            NG._getGrid(gridid).getStore().on('update', function (p1, p2, p3, p4) {
                if (d_field == p4) {
                    update_master_field();
                }
            });
            NG._getGrid(gridid).getStore().on('remove', function () {  //lqg20210222
                update_master_field();
            });
        },

        setSpliceToMasterFirstRow: function (m_field, d_field, gridid) {
            //将第一行列表字段字符串到表头
            var update_master_field = function () {
                if (NG._getGrid(gridid).getStore().data.length > 0) {
                    NG.setValue(m_field, NG._getGrid(gridid).getStore().data.items[0].data[d_field]);

                }
            }
            NG._getGrid(gridid).getStore().on('add', function () {
                update_master_field()
            });
            NG._getGrid(gridid).getStore().on('update', function (p1, p2, p3, p4) {
                if (d_field == p4) {
                    update_master_field();
                }
            });
            NG._getGrid(gridid).getStore().on('remove', function () {  //lqg20210222
                update_master_field();
            });
        },
        //-----------------------


        getValue: function (m_field) {
            //获取表头字段值
            return curForm.getItem(m_field).getValue();
        },

        setValue: function (m_field, m_field_value, nofireChange) {
            //设置表头字段值，并自动执行代码转名称
            var field = this.getItem(m_field);
            if (field) { //lqg20210204添加，解决当执行addSelectBySql()时，若有多余字段报错。
                if (!nofireChange) {
                    field.setValue(m_field_value);
                } else {
                    field.setRawValue(m_field_value);
                }
                if (this._needBatch(m_field)) {
                    BatchBindCombox([field]);
                    field.fireEvent('helpselected');//触发一下通用帮助的helpselected事件
                }
            }
        },
        getItem: function (m_field) {
            //获取表头字段控件
            return curForm.getItem(m_field);
        },
        callServer: function (funcName, arg, fieldname) {
            //简化callServer调用
            try {
                var rvres;
                callServer(funcName, [arg], function (res) {
                    if (fieldname) {
                        if (res.record.length > 0) {
                            rvres = res.record[0][fieldname];
                        }
                    } else {
                        rvres = res;
                    }
                });
                return rvres;
            } catch (e) {
                return rvres;
            }
        },

        callServerByProc: function (funcName, arg, fieldname) { //lqg20220629
            //简化callServer调用
            try {
                var rvres;
                callServer(funcName, [arg], function (res) {
                    if (fieldname) {
                        if (res.result.length > 0) {
                            rvres = res.result[0][fieldname];
                        }
                    } else {
                        rvres = res;
                    }
                });
                return rvres;
            } catch (e) {
                return rvres;
            }
        },


        callServerAsyn: function (funcName, arg, func, msg) {
            var loadMarsk = new Ext.LoadMask(document.body, { msg: msg || '加载中...', removeMask: true });
            loadMarsk.show();
            Ext.Ajax.request({
                params: {
                    'busname': busname,
                    'funcname': funcName,
                    'paramstr': [arg]
                },
                url: C_ROOT + 'SUP/ServerFuncParser/FuncParser',
                async: true, //异步请求
                success: function (response) {
                    loadMarsk.hide();
                    //{status: "ok", message: "返回datatable转json串", count: 1, record:[{"compname":"装饰一分公司"}] };
                    if (!Ext.isEmpty(response.responseText)) {
                        var resp = Ext.JSON.decode(response.responseText);
                        func(resp);
                    } else {
                        func('');
                    }
                },
                failure: function () {
                    loadMarsk.hide();
                }
            });
        },
        execServer: function (funcName, arg, fieldname) {
            //简化execServer调用
            var rvres;
            execServer(funcName, arg, function (res) {
                if (fieldname) {
                    if (res.data.length > 0) {
                        rvres = res.data[0][fieldname];
                    }
                } else {
                    rvres = res;
                }
            });
            return rvres;
        },
        dateFormat: function (date, fmt) {
            //时间格式化
            var ret;
            var dt = new Date(date)  //转换为对象，对于有时分秒的情况原代码报错lqg
            var opt = {
                "Y+": dt.getFullYear().toString(),        // 年
                "m+": (dt.getMonth() + 1).toString(),     // 月
                "d+": dt.getDate().toString(),            // 日
                "H+": dt.getHours().toString(),           // 时
                "M+": dt.getMinutes().toString(),         // 分
                "S+": dt.getSeconds().toString()          // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
            };
            for (var k in opt) {
                ret = new RegExp("(" + k + ")").exec(fmt);
                if (ret) {
                    fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
                }
            }
            return fmt;
        },
        getYmts: function () {
            //获取当前时间距离月末天数
            var now = new Date();
            return new Date(now.getYear(), now.getMonth() + 1, 0).getDate() - now.getDate();
        },
        getTs: function (date) {
            //获取任意日期对应月份的天数
            if (!date) date = new Date();
            var now = new Date(date);
            return new Date(now.getYear(), now.getMonth() + 1, 0).getDate();
        },
        dateAdd: function (interval, number, date) {
            var cd = date ? new Date(date) : new Date();
            var afi = 0;
            switch (interval) {
                case '年':
                    afi = cd.setFullYear(cd.getFullYear() + number);
                    break;
                case '月':
                    afi = cd.setMonth(cd.getMonth() + number);
                    break;
                case '日':
                    afi = cd.setDate(cd.getDate() + number);
                    break;
                case 'year':
                    afi = cd.setFullYear(cd.getFullYear() + number);
                    break;
                case 'month':
                    afi = cd.setMonth(cd.getMonth() + number);
                    break;
                case 'day':
                    afi = cd.setDate(cd.getDate() + number);
                    break;
                default:
                    afi = cd.setDate(cd.getDate() + number);
                    break;
            }
            return new Date(afi);
        },
        dateBetween: function (start, end) {
            var startDate = Date.parse(start);
            var endDate = Date.parse(end);
            if (startDate >= endDate) {
                return 0;
            }
            var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
            return days;
        },
        deleteEvent: function (funcName, arg, msg) {
            var res = this.callServer(funcName, arg);
            if (res.record && res.record.length > 0) {
                var co = this._getFirstAttr(res.record[0]);
                if (co > 0) {
                    Ext.MessageBox.alert("提示", msg);
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        },
        bindMasterSql: function (changeField, setField, funcName, parsDic) {
            //给指定控件绑定需要执行sql语句的更新事件,仅对帮助或下拉类型的控件
            //parsDic格式： {'phid':'ocode','ff':'abc'}，属性名为sql语句中@后面的值，属性值为需要获取的表头字段对应的值
            var xtp = this.getItem(changeField).xtype;
            var ev = 'change';
            if (NG._helpFieldType.includes(xtp)) {
                ev = 'helpselected';
            }
            var excute = function () {
                var csPars = {};
                for (var keybms in parsDic) {
                    csPars[keybms] = NG.getValue(parsDic[keybms]) || '';
                }
                var resCS = NG.callServer(funcName, csPars);
                if (resCS.record && resCS.record.length > 0) {
                    var firstAtr = NG._getFirstAttr(resCS.record[0]);
                    NG.setValue(setField, firstAtr);
                }
            }
            this.getItem(changeField).addListener(ev, function () {
                excute()
            });
            if (ev == 'helpselected') {
                this.getItem(changeField).addListener('change', function () {
                    excute()
                });
            }
        },
        alert: function (msg) {
            Ext.MessageBox.alert("提示", msg);
        },

        //----------lqg20210306添加------------------
        confirmThenClose: function (msg) {
            Ext.Msg.confirm("是否关闭本窗口？", msg, function (btn) {
                if (btn == "yes") {
                    window.close();
                    res = true;
                }
            });
        },//-----------------
        addDetailBySql: function (funcName, arg, isFg, gridid) {
            //执行sql，将sql返回数据插入表体
            var allrows = this.callServer(funcName, arg);
            if (allrows && allrows.record.length > 0) {
                if (isFg) {
                    NG._getGrid(gridid).getStore().removeAll();
                    NG._getGrid(gridid).getView().refresh();
                }
                NG._getGrid(gridid).getStore().insert(NG._getGrid(gridid).getStore().getCount(), allrows.record);
            }
        },
        //----------lqg20220120添加------------------
        addDetailByProc: function (funcName, arg, isFg, gridid) {
            //执行存储过程功能函数，将返回数据直接插入表体，常用于代码长度超过4000个字符的情况
            var allrows = this.callServer(funcName, arg);
            if (allrows && allrows.result.length > 0) {
                if (isFg) {
                    NG._getGrid(gridid).getStore().removeAll();
                    NG._getGrid(gridid).getView().refresh();
                }
                NG._getGrid(gridid).getStore().insert(NG._getGrid(gridid).getStore().getCount(), allrows.result);
            }
        },//-----------------------------

        addSelectBySql: function (funcName, arg, gridid, noAddfire) {  //lqg20210217添加noAddfire参数，若不需要引发add，则需true。
            var allrows = this.callServer(funcName, arg);
            if (allrows && allrows.record.length > 0) {
                var selectRow = NG._getGrid(gridid).getSelectionModel().getSelection();
                if (selectRow.length > 0) {
                    var curRow = selectRow[0];
                    for (var it in allrows.record[0]) {
                        //curRow.data[it] = allrows.record[0][it];
                        curRow.set(it, allrows.record[0][it]);  //lqg20210220修改，set方法赋值可以出发update事件。

                    }
                    if (!noAddfire) {
                        NG._getGrid(gridid).getStore().fireEvent('add', '');
                    }
                    NG._getGrid(gridid).getView().refresh();
                }
            }
        },
        //----------lqg20220120添加------------------
        addSelectByProc: function (funcName, arg, gridid, noAddfire) {  //lqg20210217添加noAddfire参数，若不需要引发add，则需true。
            var allrows = this.callServer(funcName, arg);
            if (allrows && allrows.result.length > 0) {
                var selectRow = NG._getGrid(gridid).getSelectionModel().getSelection();
                if (selectRow.length > 0) {
                    var curRow = selectRow[0];
                    for (var it in allrows.result[0]) {
                        //curRow.data[it] = allrows.record[0][it];
                        curRow.set(it, allrows.result[0][it]);  //lqg20210220修改，set方法赋值可以出发update事件。

                    }
                    if (!noAddfire) {
                        NG._getGrid(gridid).getStore().fireEvent('add', '');
                    }
                    NG._getGrid(gridid).getView().refresh();
                }
            }
        },
        //-------------------------------

        addMasterBySql: function (funcName, arg) {
            //执行sql，将sql返回的第一条数据赋值给表头字段（sql语句返回的结果集字段需要和表头字段名一致）
            var allrows = this.callServer(funcName, arg);
            if (allrows && allrows.record.length > 0) {
                for (var it in allrows.record[0]) {
                    NG.setValue(it, allrows.record[0][it]);
                }
            }
        },

        addMasterByProc: function (funcName, arg) {//-----------------------lqg 20220629增加
            //执行sql，将sql返回的第一条数据赋值给表头字段（sql语句返回的结果集字段需要和表头字段名一致）
            var allrows = this.callServer(funcName, arg);
            if (allrows && allrows.result.length > 0) {
                for (var it in allrows.result[0]) {
                    NG.setValue(it, allrows.result[0][it]);
                }
            }
        },

        //-----------------------lqg 20210203增加
        addMasterByExecServer: function (funcName, arg) {
            //调用execServer，将sql返回的第一条数据赋值给表头字段（sql语句返回的结果集字段需要和表头字段名一致）
            var allrows = this.execServer(funcName, arg);
            if (allrows && allrows.data.length > 0) {
                for (var it in allrows.data[0]) {
                    NG.setValue(it, allrows.data[0][it]);
                }
            }
        },
        //--------------------------------

        addDetailByUser: function (funcName, arg, title, wi, he, gridid, fg, widthData) {
            //执行sql，将sql返回数据弹出，提供给用户选择，将选中的数据插入表体
            var allrows = this.callServer(funcName, arg);
            if (allrows && allrows.record.length > 0) {
                //获取返回数据中列对应的中文名称，帮助列隐藏
                //创建窗体及列表，填充数据，弹出窗体
                var allcolumns = this._getGridColumns(gridid);
                var dataallfields = [];
                var dataallcolumns = [];
                for (var recordKey in allrows.record[0]) {
                    dataallfields.push(recordKey);
                    var findcolum = allcolumns.find((it) => it.dataIndex == recordKey);
                    // var findcolum=allcolumns.find(function (it) {
                    //     return it.dataIndex==recordKey;
                    // });
                    if (findcolum) {
                        if (widthData && widthData[it.dataIndex]) {
                            findcolum.width = widthData[it.dataIndex];
                        }
                        findcolum.header = '<span style="text-align:center">' + findcolum.header + '</span>';
                        dataallcolumns.push(findcolum);
                    }
                }
                this._addDetailByUserPar = { 'gridid': gridid, 'fg': fg };
                var _store = new Ext.data.JsonStore({
                    data: allrows.record, autoLoad: true, fields: dataallfields
                });
                var _forgrid = new Ext.grid.GridPanel({
                    selModel: {
                        selection: "rowmodel",
                        mode: "MULTI"
                    },
                    id: 'adddetailuerGrid',
                    region: 'center', store: _store, columns: dataallcolumns
                });
                var _window = new Ext.Window({
                    id: 'adddetailuerWin',
                    title: '<div align="left">' + title + '</div>',
                    width: wi,
                    height: he,
                    plain: true,
                    layout: 'border',
                    items: [{
                        xtype: 'panel', region: 'north', items: []
                    }, _forgrid],
                    scope: this,
                    dockedItems: [{
                        xtype: 'toolbar',
                        dock: 'bottom',
                        ui: 'footer',
                        scope: this,
                        //defaults: {minWidth: minButtonWidth},
                        items: [
                            { xtype: 'component', flex: 1 },
                            {
                                xtype: 'checkbox',
                                boxLabel: '全选',
                                name: 'selectallrow',
                                checked: false,
                                id: 'selectallrowid',
                                handler: function (checkbox, checked) {
                                    var gm = Ext.getCmp('adddetailuerGrid').getSelectionModel();
                                    if (checked) {
                                        gm.selectAll();
                                    } else {
                                        gm.deselectAll();
                                    }
                                }
                            },
                            {
                                text: '确定',
                                scope: this,
                                handler: function () {
                                    var fugai = this._addDetailByUserPar.fg;//1表示覆盖
                                    var allselectd = Ext.getCmp('adddetailuerGrid').getSelectionModel().getSelection();
                                    if (fugai == true) {
                                        NG._getGrid(this._addDetailByUserPar.gridid).getStore().removeAll();
                                        NG._getGrid(this._addDetailByUserPar.gridid).getView().refresh();
                                    }
                                    NG._getGrid(this._addDetailByUserPar.gridid).getStore().insert(NG._getGrid(this._addDetailByUserPar.gridid).getStore().getCount(), allselectd);
                                    Ext.getCmp('adddetailuerWin').close();
					//this._addDetailByUserParWin.close();
                                }
                            },
                            {
                                text: '取消',
				scope: this,
                                handler: function () {
                                    Ext.getCmp('adddetailuerWin').close();
				    //this._addDetailByUserParWin.close();
                                }
                            }
                        ]
                    }]
                });
		//this._addDetailByUserParWin = _window;
                _window.show();
            } else {
                this.alert('未查询到数据');
            }
        },

        //20220120lqg新增，满足通过存储过程获取到的数据插入
        addDetailByUserProc: function (funcName, arg, title, wi, he, gridid, fg, widthData) {
            //执行sql，将sql返回数据弹出，提供给用户选择，将选中的数据插入表体
            var allrows = this.callServer(funcName, arg);
            if (allrows && allrows.result.length > 0) {  //区别是record、result
                //获取返回数据中列对应的中文名称，帮助列隐藏
                //创建窗体及列表，填充数据，弹出窗体
                var allcolumns = this._getGridColumns(gridid);
                var dataallfields = [];
                var dataallcolumns = [];
                for (var recordKey in allrows.result[0]) {
                    dataallfields.push(recordKey);
                    var findcolum = allcolumns.find((it) => it.dataIndex == recordKey);
                    // var findcolum=allcolumns.find(function (it) {
                    //     return it.dataIndex==recordKey;
                    // });
                    if (findcolum) {
                        if (widthData && widthData[it.dataIndex]) {
                            findcolum.width = widthData[it.dataIndex];
                        }
                        findcolum.header = '<span style="text-align:center">' + findcolum.header + '</span>';
                        dataallcolumns.push(findcolum);
                    }
                }
                this._addDetailByUserPar = { 'gridid': gridid, 'fg': fg };
                var _store = new Ext.data.JsonStore({
                    data: allrows.result, autoLoad: true, fields: dataallfields
                });
                var _forgrid = new Ext.grid.GridPanel({
                    selModel: {
                        selection: "rowmodel",
                        mode: "MULTI"
                    },
                    id: 'adddetailuerGrid',
                    region: 'center', store: _store, columns: dataallcolumns
                });
                var _window = new Ext.Window({
                    id: 'adddetailuerWin',
                    title: '<div align="left">' + title + '</div>',
                    width: wi,
                    height: he,
                    plain: true,
                    layout: 'border',
                    items: [{
                        xtype: 'panel', region: 'north', items: []
                    }, _forgrid],
                    scope: this,
                    dockedItems: [{
                        xtype: 'toolbar',
                        dock: 'bottom',
                        ui: 'footer',
                        scope: this,
                        //defaults: {minWidth: minButtonWidth},
                        items: [
                            { xtype: 'component', flex: 1 },
                            {
                                xtype: 'checkbox',
                                boxLabel: '全选',
                                name: 'selectallrow',
                                checked: false,
                                id: 'selectallrowid',
                                handler: function (checkbox, checked) {
                                    var gm = Ext.getCmp('adddetailuerGrid').getSelectionModel();
                                    if (checked) {
                                        gm.selectAll();
                                    } else {
                                        gm.deselectAll();
                                    }
                                }
                            },
                            {
                                text: '确定',
                                scope: this,
                                handler: function () {
                                    var fugai = this._addDetailByUserPar.fg;//1表示覆盖
                                    var allselectd = Ext.getCmp('adddetailuerGrid').getSelectionModel().getSelection();
                                    if (fugai == true) {
                                        NG._getGrid(this._addDetailByUserPar.gridid).getStore().removeAll();
                                        NG._getGrid(this._addDetailByUserPar.gridid).getView().refresh();
                                    }
                                    NG._getGrid(this._addDetailByUserPar.gridid).getStore().insert(NG._getGrid(this._addDetailByUserPar.gridid).getStore().getCount(), allselectd);
                                    Ext.getCmp('adddetailuerWin').close();
                                }
                            },
                            {
                                text: '取消',
                                handler: function () {
                                    Ext.getCmp('adddetailuerWin').close();
                                }
                            }
                        ]
                    }]
                });
                _window.show();
            } else {
                this.alert('未查询到数据');
            }
        },
        //-------------------------------------------------------

        checkID: function (idcard) {
            //校验身份证
            //0 合法身份证，1 有非法字符，2 最后一码有非法字符，3 长度错误，4 校验错误，5 身份证为空
            var rv = 0;
            var reg1 = /^[0-9]*$/;
            if (!idcard) {
                rv = 5;
            } else if (!reg1.test(idcard.substring(0, 17))) {
                rv = 1;
            } else if (!'0123456789X'.includes(idcard.substring(idcard.length - 1))) {
                rv = 2;
            } else if (idcard.length != 15 && idcard.length != 18) {
                rv = 3;
            } else if (idcard.length == 18) {
                var yushu = (parseInt(idcard.substring(0, 1)) * 7 +
                    parseInt(idcard.substring(1, 2)) * 9 +
                    parseInt(idcard.substring(2, 3)) * 10 +
                    parseInt(idcard.substring(3, 4)) * 5 +
                    parseInt(idcard.substring(4, 5)) * 8 +
                    parseInt(idcard.substring(5, 6)) * 4 +
                    parseInt(idcard.substring(6, 7)) * 2 +
                    parseInt(idcard.substring(7, 8)) * 1 +
                    parseInt(idcard.substring(8, 9)) * 6 +
                    parseInt(idcard.substring(9, 10)) * 3 +
                    parseInt(idcard.substring(10, 11)) * 7 +
                    parseInt(idcard.substring(11, 12)) * 9 +
                    parseInt(idcard.substring(12, 13)) * 10 +
                    parseInt(idcard.substring(13, 14)) * 5 +
                    parseInt(idcard.substring(14, 15)) * 8 +
                    parseInt(idcard.substring(15, 16)) * 4 +
                    parseInt(idcard.substring(16, 17)) * 2) % 11;
                var jy;
                switch (yushu) {
                    case 0:
                        jy = '1';
                        break;
                    case 1:
                        jy = '0';
                        break;
                    case 2:
                        jy = 'X';
                        break;
                    case 3:
                        jy = '9';
                        break;
                    case 4:
                        jy = '8';
                        break;
                    case 5:
                        jy = '7';
                        break;
                    case 6:
                        jy = '6';
                        break;
                    case 7:
                        jy = '5';
                        break;
                    case 8:
                        jy = '4';
                        break;
                    case 9:
                        jy = '3';
                        break;
                    case 10:
                        jy = '2';
                        break;
                    default:
                        jy = '';
                        break;
                }
                if (idcard.substring(17, 18) != jy) rv = 4;
            }
            return rv;
        },
        addToolBar: function (index, btnTxt, icon, func, itemId) {
            //给toolbar添加按钮，加到列表还是明细界面需要通过在不通的钩子函数中执行本函数来进行控制
            var tb = Ext.getCmp('toolbar');
            if (itemId) {
                tb.insert(index, { text: btnTxt, itemId: itemId, iconCls: 'iconfont ' + icon, handler: func });
            } else {
                tb.insert(index, { text: btnTxt, iconCls: 'iconfont ' + icon, handler: func });
            }
        },
        validateEmpty: function (fields) {
            //判断表头字段是否为空，为空则返回false并弹出提示
            var rv = true;
            for (var i = 0; i < fields.length; i++) {
                if (!NG.getItem(fields[i]).getValue()) {
                    NG.alert(NG.getItem(fields[i]).fieldLabel + '为空，请先录入该字段');
                    rv = false;
                    break;
                }
            }
            return rv;
        },
        setFieldsHeight: function (height, name) {
            var css = document.createElement('style');
            if (name) {
                var lineheightCss = "line-height: " + height + "px !important;";
                if (NG.getItem(name).el.query('textarea').length > 0) {
                    lineheightCss = "";
                }
                css.innerHTML = "#" + name + " .x-form-trigger,#" + name + " .x-form-display-field,#" + name + " .x-form-text,#" + name + " .x-form-item-label {\n" +
                    "height: " + height + "px !important;\n" +
                    lineheightCss +
                    "margin-top:0 !important;\n" +
                    "background-position-y: center !important;}\n";
            } else {
                css.innerHTML = ".x-form-trigger,.x-form-display-field,input.x-form-text,.x-form-item-label {\n" +
                    "height: " + height + "px !important;\n" +
                    "line-height: " + height + "px !important;\n" +
                    "margin-top:0 !important;\n" +
                    "background-position-y: center !important;}\n";
            }
            document.head.append(css);
        },
        setGridTop: function (top, gridid) {
            var gg = NG._getGrid(gridid);
            var css = document.createElement('style');
            css.innerHTML = '#' + gg.id + '{top:' + top + 'px !important;}';
            document.head.append(css);
        },
        addDefaultQuery: function (kv) {
            //设置查询条件默认值
            this._init();
            if (!this.isDetail) {
                var vp = Ext.getCmp('viewPort');
                var qp = vp.items.items[1];
                for (var it in kv) {
                    var f = qp.down('[name=' + it + ']');
                    if (f) {
                        f.setValue(kv[it]);
                    }
                }
            }
        },
        addDefaultQueryEx: function (datepart, number, str) {
            //设置单据列表日期查询默认,datepart可以分别为“year”、“monht”、“day”；number负数；str为日期字段名，需查询，缺省指“Bill_dt"
            str = str ? str : "Bill_dt";
            var nameStart = str + "*date*ge*";  //原始
            var nameEnd = str + "*date*le*";

            var nameStart1 = str + "*date*ge*0";  //lqg20211010添加
            var nameEnd1 = str + "*date*le*0";

            var nameStart2 = str + "*date*ge*1";  //lqg20211010添加
            var nameEnd2 = str + "*date*le*1";

            var valueEnd = new Date();
            var valueStart = this.dateAdd(datepart, number, valueEnd);
            var obj = {};

            obj[nameStart] = valueStart;
            obj[nameEnd] = valueEnd;

            obj[nameStart1] = valueStart;
            obj[nameEnd1] = valueEnd;

            obj[nameStart2] = valueStart;
            obj[nameEnd2] = valueEnd;

            this.addDefaultQuery(obj);

        },

        setFieldBodyColor: function (fieldName, colorExp) {
            var f = this._getForm().getItem(fieldName);
            if (f) {
                var li = f.el.query("[name=" + fieldName + "]");
                if (li && li.length > 0) {
                    li[0].style.color = colorExp;
                }
            }
        },
        negativeNumberSetRedForMaster: function () { //------------lqg20210313------
            //将表头所有数字类型的字段添加change事件，若为负值显示为红色。
            var myArr = [];
            if (curForm.fieldSets) {
                Ext.each(curForm.fieldSets, function (it, index) {
                    if (it.xtype == 'ngNumber') {
                        myArr = myArr.concat(it);
                    } else if (it.xtype == 'fieldset') {
                        Ext.each(it.fieldRows, function (onerow) {
                            Ext.each(onerow, function (oneField) {
                                if (oneField.xtype == 'ngNumber') {
                                    myArr = myArr.concat(oneField);
                                }
                            });
                        });
                    }
                })
            } else {
                if (typeof curForm.fields == "object") {   //精准布局
                    myArr = curForm.fields
                } else {                        //非精准布局
                    Ext.each(curForm.fieldRows, function (it, index) {
                        myArr = myArr.concat(it);
                    })
                }
            }
            Ext.each(myArr, function (it, index) {  //curForm.fields
                if (it.xtype == 'ngNumber') {
                    curForm.getItem(it.id).on('change', function (params) {
                        var f = curForm.getItem(it.id);
                        var li = f.el.query("[name=" + it.name + "]");
                        if (li && li.length > 0) {
                            if (curForm.getItem(it.id).getValue() < 0) {
                                li[0].style.color = 'red';
                            } else {
                                li[0].style.color = 'blue';
                            }
                        }
                    })
                }
            });
        },
        negativeNumberSetRedForGrid: function () {
            Ext.each(this._getGrid().columns, function (it, index) {
                if (it.editor && it.editor.xtype == 'ngNumber') {
                    var old = '', end = 0;
                    old = it.renderer.toString();
                    var start = old.indexOf(",'");
                    if (start > 0) {
                        end = old.indexOf("')", start);
                    }
                    if (start > 0 && end > 0) {
                        if (old.indexOf('%') > 0) {
                            NG._getGrid().getColumn(it.dataIndex).renderer = function (val, m) {
                                if (val < 0) {
                                    m.style = "color:red;";
                                } else {
                                    m.style = "color:rgb(0,0,255);";
                                }
                                return Ext.util.Format.number(val * 100, old.substring(start + 2, end));
                            }
                        } else {
                            NG._getGrid().getColumn(it.dataIndex).renderer = function (val, m) {
                                if (val < 0) {
                                    m.style = "color:red;";
                                } else {
                                    m.style = "color:rgb(0,0,255);";
                                }
                                return Ext.util.Format.number(val, old.substring(start + 2, end));
                            }
                        }

                    } else {
                        NG._getGrid().getColumn(it.dataIndex).renderer = function (val, m) {
                            if (val < 0) {
                                m.style = "color:red;";
                            } else {
                                m.style = "color:rgb(0,0,255);";
                            }
                            return Ext.util.Format.number(val, "000,000.00");
                        }
                    }
                }
            })
        },
        setComboColumnColor: function (columnName, colorDic, gridid) {
            var toCol = NG._getGrid(gridid).columns.find(it => it.dataIndex == columnName);
            if (toCol && toCol.editor.xtype == 'ngComboBox') {
                var codeName = toCol.editor.data;
                toCol.renderer = ((r, m, d) => {
                    var valName = '';
                    if (codeName.find(it => it.code == r)) {
                        valName = codeName.find(it => it.code == r).name;
                        if (colorDic[r]) {
                            m.style = "color:" + colorDic[r];
                        } else {
                            m.style = "color:rgb(0,0,255);";
                        }
                    } else {
                        m.style = "color:rgb(0,0,255);";
                    }
                    return valName
                })
            }
        },
        setColumnColorExp: function (columnName, color, exp, gridid) {
            var toCol = NG._getGrid(gridid).columns.find(it => it.dataIndex == columnName);
            var expFields = this._getExpField(exp);
            var exp2 = exp;
            for (var j = 0; j < expFields.length; j++) {
                exp2 = exp2.replace(new RegExp('{' + expFields[j] + '}', 'g'), "rowData.data." + expFields[j]);
            }
            if (toCol) {
                if (toCol.editor.xtype == 'ngNumber') {
                    var old = '', end = 0;
                    old = toCol.renderer.toString();
                    var start = old.indexOf(",'");
                    if (start > 0) {
                        end = old.indexOf("')", start);
                    }
                    if (end > 0 && start > 0) {
                        var numberForat = old.substring(start + 2, end);
                        toCol.renderer = function (val, m, rowData) {
                            if (eval(exp2)) {
                                m.style = "color:" + color;
                            } else {
                                m.style = "color:rgb(0,0,255);";
                            }
                            return Ext.util.Format.number(val, numberForat);
                        }
                    }
                } else {
                    toCol.renderer = function (val, m, rowData) {
                        if (eval(exp2)) {
                            m.style = "color:" + color;
                        } else {
                            m.style = "color:rgb(0,0,255);";
                        }
                        return val;
                    }
                }
            }
        },
        setFieldLabelColor: function (fieldName, colorExp) {
            var f = this._getForm().getItem(fieldName);
            if (f) {
                var li = f.el.query("label");
                if (li && li.length > 0) {
                    li[0].style.color = colorExp;
                }
            }
        },
        setRowColor: function (valueExp, colorDic, gridid) {
            if (!gridid) gridid = '';
            var expFields = this._getExpField(valueExp);
            var css = document.createElement('style');
            var colorcss = '';
            for (var i = 0; i < colorDic.length; i++) {
                colorcss += " .jncjspecial-row" + gridid + i + " td div{color:" + colorDic[i].value + " !important}";
            }
            css.innerHTML = colorcss;
            document.head.append(css);
            NG._getGrid(gridid).getView().getRowClass = function (r, rowIndex) {
                var exp2 = valueExp;
                for (var j = 0; j < expFields.length; j++) {
                    if (gridid) {
                        exp2 = exp2.replace(new RegExp('{' + expFields[j] + '}', 'g'), "NG._getGrid('" + gridid + "').getStore().data.items[" + rowIndex + "].data." + expFields[j]);
                    } else {
                        exp2 = exp2.replace(new RegExp('{' + expFields[j] + '}', 'g'), "NG._getGrid().getStore().data.items[" + rowIndex + "].data." + expFields[j]);
                    }
                }
                var evvalue = eval(exp2);
                var rvcss = '';
                for (var k = 0; k < colorDic.length; k++) {
                    if (evvalue == colorDic[k].key) {
                        rvcss = "jncjspecial-row" + gridid + k;
                    }
                }
                return rvcss;
            }
        },
        round: function (num, int) {  //lqg20210219添加
            //四舍五入到指定位数，返回数值型。
            if (!int || (int >= 0 && typeof (int) == 'number')) {
                var n = Math.round(int || 0);
                var m = Math.pow(10, n);
                var y = Math.round(num * m) / m
                return y
            }
        },
        trim: function (str, type) {  //lqg20210219添加
            // 去除字符串空格。type 1-所有空格 2-前后空格 3-前空格 4-后空格
            var n = type || 1
            switch (n) {
                case 1:
                    return str.replace(/\s+/g, "");
                case 2:
                    return str.replace(/(^\s*)|(\s*$)/g, "");
                case 3:
                    return str.replace(/(^\s*)/g, "");
                case 4:
                    return str.replace(/(\s*$)/g, "");
                default:
                    return str;
            }
        },
        padLeft: function (num, length) {  //lqg20210222添加
            // 给数字num左侧补0，使其长度为length
            return new Array(length - (num + '').length + 1).join('0') + num;
        },

        setFormTabKey: function (key) {
            var map = new Ext.KeyMap(NG._getForm().el, {
                key: key || Ext.EventObject.ENTER,
                fn: function (key, e) {
                    var target = [], ex_target = NG._getForm().el.query(':focusable');
                    Ext.each(ex_target, function (it, index) {
                        if (!NG._getForm().getItem(it.name).readOnly) {
                            target.push(it);
                        }
                    });
                    var el = e.target, ln = target.length;
                    for (var i = 0; i < ln; i++) {
                        if (target[i] == el) {
                            if (i + 1 == ln) {
                                target[0].focus();
                            } else {
                                target[i + 1].focus();
                            }
                        }
                    }
                    ;
                }
            });
            map.enable();
        },
        setGridTabKey: function () {
            Ext.grid.plugin.CellEditing.override({
                onSpecialKey: function (ed, field, e) {
                    var sm;

                    // keyCode: 37(左), 38(上), 39(右), 40(下)
                    if (e.getKey() === 38 || e.getKey() === 40) {
                        if (field.xtype == 'combo') {
                            return;
                        }
                        e.stopEvent();
                        if (ed) {
                            ed.onEditorTab(e);
                        }
                        sm = ed.up('tablepanel').getSelectionModel();
                        if (sm.onEditorTab) {
                            return sm.onEditorTab(ed.editingPlugin, e);
                        }
                    } else if (e.getKey() === e.TAB || e.getKey() === e.ENTER || e.getKey() == 37 || e.getKey() == 39) {
                        e.stopEvent();
                        if (ed) {
                            ed.onEditorTab(e);
                        }
                        sm = ed.up('tablepanel').getSelectionModel();
                        if (sm.onEditorTab) {
                            return sm.onEditorTab(ed.editingPlugin, e);
                        }
                    }
                }
            });
            Ext.selection.RowModel.override({
                onEditorTab: function (editingPlugin, e) {
                    var me = this,
                        view = me.views[0],
                        record = editingPlugin.getActiveRecord(),
                        header = editingPlugin.getActiveColumn(),
                        position = view.getPosition(record, header),
                        direction = e.shiftKey ? 'left' : 'right';
                    // keyCode: 37(左), 38(上), 39(右), 40(下)
                    if (e.getKey() == 37) {
                        direction = 'left';
                    } else if (e.getKey() == 38) {
                        direction = 'up';
                    } else if (e.getKey() == 40) {
                        direction = 'down';
                    }
                    do {
                        position = view.walkCells(position, direction, e, me.preventWrap);
                    } while (position && (!editingPlugin.startEditByPosition(position)));
                }
            });
        },
        ///小驼峰方法名
        checkDataDetail: function (str, msg, table) {
            if (table == null || table == '' || typeof (msg) == "undefined") {
                table = tablenameM.replace('_m', '_d')
            }

            var dgrid1 = Ext.getCmp(table + 'grid');
            var dstore1 = dgrid1.store;
            var NumTest = new RegExp(/^-\d+(\.\d+)$/);
            var pattern = new RegExp("[\+ \- \* \/ \== \< \> \<= \>= \!=]");
            var arr = str.split(pattern)
            if (dstore1.getCount() > 0) {
                for (var i = 0; i < dstore1.getCount(); i++) {
                    var result = '';
                    arr.forEach(function (item, index, arr) {
                        if (arr[index] !== '' && item !== '') {
                            if (NumTest.test(item)) {

                            } else {
                                var value = Ext.Number.from(dstore1.getAt(i).get(item), 0) == '' ? '0' : Ext.Number.from(dstore1.getAt(i).get(item), 0);
                                result += item + "=" + value + "; ";
                            }
                        }
                    })
                    eval(result);
                    var flg = eval(str);
                    if (!flg) {
                        Ext.Msg.alert('提示', i + 1 + '行' + msg);
                        curToolbar.get('save').setDisabled(false);//需要把按钮重新置为可用状态
                        return false;
                    } else {
                        return true;
                    }
                }
            }
        },
        checkDataMain: function (str, msg, table) {
            if (table == null || table == '' || typeof (msg) == "undefined") {
                table = tablenameM
            }
            var NumTest = new RegExp(/^-\d+(\.\d+)$/);
            var pattern = new RegExp("[\+ \- \* \/ \== \< \> \<= \>= \!=]");
            var arr = str.split(pattern)
            var result = '';

            arr.forEach(function (item, index, arr) {
                if (arr[index] !== '' && item !== '') {
                    if (NumTest.test(item)) {

                    } else {
                        var value = curForm.getItem(item).getValue() == '' ? '0' : curForm.getItem(item).getValue();
                        result += item + "=" + value + "; ";
                    }

                }
            })
            eval(result);
            var flg = eval(str);
            if (!flg) {
                Ext.Msg.alert('提示', msg);
                curToolbar.get('save').setDisabled(false);//需要把按钮重新置为可用状态
                return false;
            } else {
                return true;
            }
        },
        checkOnlySaveMain: function (arr, msg) {
            var sqlParam = tablenameM;
            var msgInner = '';
            arr.forEach(function (item, index, array) {
                var value = NG.getValue(item) || "0";
                if (NG.getItem(item).xtype == 'ngDate') {
                    value = NG.dateFormat(value, 'YYYY-mm-dd');
                }
                msgInner += (curForm.getItem(item).fieldLabel == '' ? item : curForm.getItem(item).fieldLabel) + ', ';
                if (index == 0) {
                    sqlParam += ' where ' + item + "='" + value + "'";

                } else {
                    sqlParam += ' and ' + item + "='" + value + "'";
                }
            })
            msgInner += '值数据库已存在，请重新录入';
            if (msg == null || msg == '' || typeof (msg) == "undefined") {
                msg = msgInner;
            }
            var phid = curForm.getItem('phid').getValue();
            sqlParam += ' and phid ' + "<>'" + phid + "'";
            console.log(sqlParam);
            var count = NG.execServer('保存唯一性判断', { 'sql': sqlParam }, 'num');
            console.log("查询结果:" + count);
            if (count == 0) {
                return true;
            } else {
                NG.alert(msg);
                curToolbar.get('save').setDisabled(false);//需要把按钮重新置为可用状态
                return false;
            }

        },
        checkOnlySaveDetail: function (arr, msg, table) {
            if (table == null || table == '' || typeof (msg) == "undefined") {
                table = tablenameM.replace('_m', '_d')
            }
            var msgInner = '';
            var dgrid1 = Ext.getCmp(table + 'grid');
            var dstore1 = dgrid1.store;
            var sqlParam = table;
            if (dstore1.getCount() > 0) {
                var str = '';
                for (var i = 0; i < dstore1.getCount(); i++) {
                    var strInner = '';
                    arr.forEach(function (item, index, array) {
                        //var value = Ext.Number.from(dstore1.getAt(i).get(item), 0);  //检测唯一性无效，李庆广20210608改为下句。
                        var value = dstore1.getAt(i).get(item);
                        if (index == 0) {
                            strInner += value;
                        } else {
                            strInner += "-" + value;
                        }
                    })
                    if (i == 0) {
                        str += "'" + strInner + "'";
                    } else {
                        str += ",'" + strInner + "'";
                    }
                }
                str = "(" + str + ")";
                var name = "";
                for (var j = 0; j < arr.length; j++) {
                    if (j == 0) {
                        name += "CAST(ISNULL(" + arr[j] + ", '0') AS varchar(max))";
                        msgInner += curGrid.getColumn(arr[j]).text == '' ? item : curGrid.getColumn(arr[j]).text;
                    } else {
                        name += "+'-'+" + "CAST(ISNULL(" + arr[j] + ", '0') AS varchar(max))";
                        msgInner += ',' + curGrid.getColumn(arr[j]).text == '' ? item : curGrid.getColumn(arr[j]).text;
                    }
                }
                sqlParam += ' where ' + name + " in " + str;
                msgInner += '值数据库已存在，请重新录入';
                if (msg == null || msg == '' || typeof (msg) == "undefined") {
                    msg = msgInner;
                }
                var phid = curForm.getItem('phid').getValue();
                sqlParam += ' and m_code ' + "<>'" + phid + "'";
                console.log(sqlParam);
                var count = NG.execServer('保存唯一性判断', { 'sql': sqlParam }, 'num');
                console.log("查询结果:" + count);
                if (count == 0) {
                    return true;
                } else {
                    NG.alert(msg);
                    curToolbar.get('save').setDisabled(false);//需要把按钮重新置为可用状态
                    return false;
                }
            } else {
                return true;
            }

        },
        checkOnlySaveLocal: function (arr, msg, table) {
            if (table == null || table == '' || typeof (msg) == "undefined") {
                table = tablenameM.replace('_m', '_d')
            }
            var msgInner = '';
            var dgrid1 = Ext.getCmp(table + 'grid');
            var dstore1 = dgrid1.store;
            var str = [];
            if (dstore1.getCount() > 0) {
                for (var T = 0; T < arr.length; T++) {
                    msgInner += curGrid.getColumn(arr[T]).text == '' ? item : curGrid.getColumn(arr[T]).text + ', ';
                    for (var i = 0; i < dstore1.getCount(); i++) {
                        var value = dstore1.getAt(i).get(arr[T]);   //  var value = Ext.Number.from(dstore1.getAt(i).get(arr[T]), 0);
                        if (T == "0") {
                            str.push(value);
                        } else {
                            str[i] += value;
                        }
                    }
                }
                msgInner += '值本表已存在，请重新录入';
                if (msg == null || msg == '' || typeof (msg) == "undefined") {
                    msg = msgInner;
                }
                let resultArrs = str.filter(function (ele, index, self) {
                    return self.indexOf(ele) === index;
                });
                if (resultArrs.length !== str.length) {
                    NG.alert(msg);
                    curToolbar.get('save').setDisabled(false);//需要把按钮重新置为可用状态
                    return false;
                }
                return true;
            } else {
                return true;
            }

        },
        checkNullSaveDetail: function (str, param, msg, table) {
            if (table == null || table == '' || typeof (table) == "undefined") {
                table = tablenameM.replace('_m', '_d')
            }

            var dgrid1 = Ext.getCmp(table + 'grid');
            var dstore1 = dgrid1.store;
            var NumTest = new RegExp(/^-\d+(\.\d+)$/);
            var pattern = new RegExp("[\+ \- \* \/ \== \< \> \<= \>= \!=]");
            var arr = str.split(pattern)
            if (dstore1.getCount() > 0 && param.length > 0) {
                for (var i = 0; i < dstore1.getCount(); i++) {
                    var result = '';
                    arr.forEach(function (item, index, arr) {
                        if (arr[index] !== '' && item !== '') {
                            if (NumTest.test(item)) {

                            } else {
                                var value = Ext.Number.from(dstore1.getAt(i).get(item), 0) == '' ? '0' : Ext.Number.from(dstore1.getAt(i).get(item), 0);
                                result += item + "=" + value + "; ";
                            }
                        }
                    })
                    eval(result);
                    var flg = eval(str);
                    if (flg) {
                        param.forEach(function (item, index, param) {
                            var value = Ext.Number.from(dstore1.getAt(i).get(item), 0) == '' ? '' : Ext.Number.from(dstore1.getAt(i).get(item), 0);
                            var parmaName = curGrid.getColumn(item).text;
                            if (value == '' || value == null || typeof (value) == "undefined") {
                                if (msg == '' || msg == null || typeof (msg) == "undefined") {
                                    msg = parmaName + "不可为空";
                                }
                                NG.alert(msg);
                                curToolbar.get('save').setDisabled(false);//需要把按钮重新置为可用状态
                                return false;
                            }
                        })
                    } else {
                        return true;
                    }
                }
            }
        },
        checkMustInput: function (columnName, exp, gridid) {
            var curentGrid = this._getGrid(gridid);
            var expFields = this._getExpField(exp);
            var store = curentGrid.getStore();
            var checkAll = true;
            for (var i = 0; i < store.data.items.length; i++) {
                var curRow = store.data.items[i].data;
                var exp2 = exp;
                for (var j = 0; j < expFields.length; j++) {
                    if (gridid) {
                        exp2 = exp2.replace(new RegExp('{' + expFields[j] + '}', 'g'), "NG._getGrid('" + gridid + "').getStore().data.items[" + i + "].data." + expFields[j]);
                    } else {
                        exp2 = exp2.replace(new RegExp('{' + expFields[j] + '}', 'g'), "NG._getGrid().getStore().data.items[" + i + "].data." + expFields[j]);
                    }
                }
                var evvalue = eval(exp2);
                var ctype = curentGrid.getColumn(columnName).editor.xtype;
                if (evvalue) {
                    if ((ctype == 'ngNumber' && curRow[columnName] == 0) || (ctype != 'ngNumber' && !curRow[columnName])) {
                        checkAll = false;
                        this.alert('第' + +(i + 1) + '行，[' + curentGrid.getColumn(columnName).text + ']列输入不能为空');
                        curToolbar.get('save').setDisabled(false);
                        break;
                    }
                }
            }
            return checkAll;
        },
        setGridReadOnlyExp: function (columnName, exp, gridid) {
            var ce = this._getGrid(gridid).getCellEditing();
            var expFields = this._getExpField(exp);
            ce.on('beforeedit', function (editor, context) {
                if (context.field == columnName) {
                    var exp2 = exp;
                    for (var j = 0; j < expFields.length; j++) {
                        exp2 = exp2.replace(new RegExp('{' + expFields[j] + '}', 'g'), "context.record.data." + expFields[j]);
                    }
                    var evvalue = eval(exp2);
                    return evvalue;
                }
            })
        },
        setFieldUnit: function (fName, unit, wi) {
            var fi = this.getItem(fName);//x-form-item-body
            var ii = fi.el.query('.x-form-item-body')[0];
            var pa = ii.parentElement;
            var nn = document.createElement('td');
            nn.innerText = unit;
            if (!wi) wi = '15px';
            nn.style.width = wi;
            pa.appendChild(nn);
        },
        setFieldLabelWidth: function (fields, width) {
            if (typeof (fields) == 'string') {
                fields = [fields];
            }
            Ext.each(fields, function (it, index) {
                var fi = NG.getItem(it);
                if (fi) {
                    var la = fi.el.query('label')[0];
                    la.style.width = width + 'px';
                    la.style.textAlign = 'left';
                    la.parentElement.width = width + 'px';
                }
            });
        },
        openCustomFunc: function (title, tname, id) {
            var buscode = 'E' + tname.replace('p_', '').replace('_m', '').toUpperCase();
            var url = C_ROOT + 'SUP/CustomIntegrate/CustomIntegrateEdit?otype=view&hastitle=1&id=' + id;
            url += '&customBusCode=' + buscode;
            $OpenTab(title + '-查看', url);
        },

        openCustomFuncEdit: function (title, tname, id) {//lqg20221126
            var buscode = 'E' + tname.replace('p_', '').replace('_m', '').toUpperCase();
            var url = C_ROOT + 'SUP/CustomIntegrate/CustomIntegrateEdit?otype=edit&hastitle=1&id=' + id;
            url += '&customBusCode=' + buscode;
            $OpenTab(title + '-编辑', url);
        },
        negativeNumberSetZeroForMaster: function () { //------------lqg20210928------
            //将表头所有数字类型的字段初始化为0。
            var myArr = [];
            if (curForm.fieldSets) {
                Ext.each(curForm.fieldSets, function (it, index) {
                    if (it.xtype == 'ngNumber') {
                        myArr = myArr.concat(it);
                    } else if (it.xtype == 'fieldset') {
                        Ext.each(it.fieldRows, function (onerow) {
                            Ext.each(onerow, function (oneField) {
                                if (oneField.xtype == 'ngNumber') {
                                    myArr = myArr.concat(oneField);
                                }
                            });
                        });
                    }
                })
            } else {
                if (typeof curForm.fields == "object") {   //精准布局
                    myArr = curForm.fields
                } else {                        //非精准布局
                    Ext.each(curForm.fieldRows, function (it, index) {
                        myArr = myArr.concat(it);
                    })
                }
            }
            Ext.each(myArr, function (it, index) {  //curForm.fields
                if (it.xtype == 'ngNumber') {
                    curForm.getItem(it.id).setValue(0.0)  //it属性及方法不全，需要根据it的id再获取一遍对象
                }
            });
        },

    };
    window.NG = NG;
})(window);
